package tron.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class TronOncePerRequestFilter extends OncePerRequestFilter  {

    /**
     * 判断需要拦截的路径，或者给某些路径放行。
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        //不拦截的地址：读取配置文件，或者从数据源获取
        List<String> ignoreURL = Arrays.asList("webjars","swagger-resources","api-docs","doc.html","login","logout","favicon.ico");
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        boolean isIgnore = false;
        for (String s : ignoreURL) {
            if (requestURI.toLowerCase().contains(s)) {
                isIgnore = true;
                break;
            }
        }
        //不过滤的地址返回true
        return isIgnore;
    }

    /**
     *
     *  拦截的规则校验
     *
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("======TronOncePerRequestFilter======拦截请求路径url:{}",request.getRequestURL());
        //这里添加验证逻辑
        String token = request.getHeader("Token");
        log.info("======Authorization信息：======{}", token);
        // todo 根据token获取用户信息，添加用户信息到当前线程
        request.setAttribute("presentUserId","0001");
//        if (token == null) {
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("text/html;charset=utf-8");
//            String msg = "Authorization信息获取失败";
//            response.getWriter().write("{\"msg\":" + msg + ",\"code\":400}");
//        }
        filterChain.doFilter(request, response);
    }

}
